import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // 开启进度条
  NProgress.start()

  // 修改页面title
  document.title = getPageTitle(to.meta.title)

  // 判断cookie中是否保存用户token
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 如果用户已登录切当前跳转路由是login，则将其重定向到应用首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 判断是否拥有权限
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // 拉取用户数据获取用户权限
          // 提示：用户权限必须是个对象数组：如['admin']or,['developer', 'editor']
          const { roles } = await store.dispatch('user/getInfo')

          // 基于角色权限生成动态路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // 动态添加路由
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 没有用户token信息

    if (whiteList.indexOf(to.path) !== -1) {
      // 判断是否访问的白名单路径
      next()
    } else {
      // 如果访问的路径没有访问权限，则统一重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 全局后置守卫钩子中结束进度条
  NProgress.done()
})
